<template>
  
    <div class="form-con">
      <el-form
        ref="basicForm"
        :model="basicForm"
        :rules="basicRules"
        label-width="100px"
        class="demo-ruleForm"
      >
   
      <section class="product-border">
        <h2>基本信息</h2>
        <div class="form-main">
            <el-form-item
            label="商品名称"
            prop="product_name"
          >
            <el-input
              v-model="basicForm.product_name"
              placeholder="请输入产品名称"
              maxlength="50"
              show-word-limit 
            />
          </el-form-item>
          <el-form-item label="品牌" prop="brand_id">
            <el-select v-model="basicForm.brand_id" placeholder="请选择">
              <el-option 
                  v-for="item in brandList"
                    :key="item.brand_id"
                    :label="item.name"
                    :value="item.brand_id" />

            </el-select>
          </el-form-item>
          <el-form-item label="类目" prop="category_id">
            <el-select v-model="basicForm.category_id" placeholder="请选择">
              <el-option  v-for="item in categoryList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"/>

            </el-select>
          </el-form-item>
          <el-form-item
            label="短描述"
            prop="keyword"
          >
            <el-input
              v-model="basicForm.keyword"
              placeholder="请输入短描述"
              maxlength="14"
              show-word-limit 
            />
          </el-form-item>
          <el-form-item label="服务保障" prop="feature">
            <el-select v-model="basicForm.feature" multiple placeholder="请选择（多选）">
              <el-option
                v-for="item in serviceList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="功效作用"
            prop="efficacy"
          >
            <el-input
              v-model="basicForm.efficacy"
              placeholder="以逗号分开，最多5个"
            />
          </el-form-item>
          <el-form-item
            label="排序值"
            prop="sort"
          >
            <el-input v-model="basicForm.sort" />
          </el-form-item>
      </el-form-item>
      </div>
  </section>
   <section class="product-border">
        <h2>图文详情</h2>
        <div class="form-main">
           <el-form-item
          label="产品图片"
          prop="images"
          class="require"
        >
        
          <el-upload
         
            action="http://49.233.69.175:8001/img"
            list-type="picture-card"
            name="uploadFile"
            ref="uploadFile"
            :on-preview="handlePictureCardPreview"
            :on-success="successHandle"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :before-upload="beforeAvatarUpload"
            :limit="12"
          >
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="basicForm.images.image_url" alt="" v-if="dialogVisible">
          </el-dialog>
         
            
           

            <ul v-if="imagesReceive.length!==0" class="receive-image">
              <li v-for="(item,index) in imagesReceive" :key="index">
                <i class="el-icon-close delete-img" @click="deleteImg(item,index)"></i>
                <img :src="formatImage(item.image_url)" alt=""  width="146px" height="146px"> 
              </li>
            </ul>
            <div
              slot="trigger"
              class="uploadImgCon"
            >
              <i class="el-icon-plus uploadImgIcon" />
            
            </div>
            <div slot="tip">图片大小?px*?px，图片大小小于1MB，支持jpg\png\jpeg格式的图片，最多上传12张</div>

          </el-upload>
        
        </el-form-item>
        <el-form-item
          label="详情描述"
          prop="content"
        >
         <!--  <el-input
            v-model="basicForm.content"
            type="textarea"
            :rows="10"
            maxlength="200"
            show-word-limit
          /> -->
          <markdown-editor v-model="basicForm.content" />
        </el-form-item>

        </div>
    </section>
        <!-- <el-button type="primary" style="margin-left:30%" @click="saveBaic('basicForm')">保存</el-button>
         -->
         <el-button type="primary" style="margin-left:30%" @click="savelp">保存</el-button>
    </el-form>
  </div>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor'
import {addProduct,getBrandList,getProductDetail,putProductDetail,deleteImg} from '@/api/product'
import {getCateList,fetchList} from '@/api/hopeTravel/category'
export default {
  components:{
    'markdown-editor':MarkdownEditor
  },
  data() {
    return {
      num:0,//图片轮播
      basicForm: {
        product_name: '', // 商品名称
        brand_id: '', // 品牌
        category_id: '', // 类目
        keyword: '', // 短描述
        feature: [], // 服务保障
        efficacy: '', // 功效作用
        sort: '', // 排序值 
        images:[],  //图片数组
        content:'',//图文描述
      },
      imageList:[],//做删除的缓冲用
      imagesReceive:[],//接收图片的数组
      specsBufferSubmit:[],//图片为提交引起的后端返回参数error  缓冲解决
     /*  basicRules: {
        // productImg: [{required: true, message: '请输入品牌名称', trigger: 'blur'}],
        product_name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        brand_id: [{ required: true, message: '请输入品牌', trigger: 'change' }],
        category_id: [{ required: true, message: '请输入类目', trigger: 'change' }],
        feature: [{ required: true, message: '请输入服务保障', trigger: 'change' }],    
        sort:[{ required: true, message: '请输入排序', trigger: 'blur' }],
      }, */
      serviceList: [
        { label: '售后无忧', value: '1' },
        { label: '正品保障', value: '2' },
        { label: '快速退款', value: '3' },
        { label: '专属客服', value: '4' },
        { label: '产地直采保障', value: '5' }], // 服务保障列表
     
        brandList:[],//接口接收到的品牌列表
        categoryList:[],//接口接收到的类目列表
        dialogVisible:false, //显示图片
    }
  },
  created(){
    // this.getBrandlist();
    // this.getCatelist();
    //  if(this.isEdit){
    //   this.getDetail(this.$route.params.id); 
    // }
  },
  mounted(){
    // this.play(); //开始轮播图片
  },
  computed:{
    //判断是否是编辑页面
    isEdit(){
      return this.$route.path.includes('edit')
    },
  },
  methods: {
    savelp(){
      fetchList().then(res=>{
        console.log(res);
        
      })
    },
    deleteImg(item,index){
      
      this.$confirm('是否删除该图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
      
            deleteImg(item.image_id).then(res=>{
            if(res.code === 0){
              this.imagesReceive.splice(index,1);
              this.$notify({
                message: '删除图片成功',
                type: 'success',
                duration: 2000,
              })
            }
          })
         
          
           
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
      
    })
    },
   
    //获取品牌列表
    getBrandlist(){
      getBrandList({page_size:100}).then(res=>{
        if(res.code === 0){
          this.brandList = res.data.items;
        }
        
      })
    },
    //获取分类列表
    getCatelist(){
      getCateList({page_size:100}).then(res=>{
         if(res.code === 0){
          this.categoryList = res.data.items;
        }
      })
    },
     //获取详情
    getDetail(id){
      let dataList = {'page':1,'page_size':20}
      getProductDetail(id,dataList).then(res=>{
          this.basicForm = res.data;
          
          this.imagesReceive = res.data.images
      
      })
    },
    // 提交表单
    saveBaic(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          
     
          this.basicForm.images = this.basicForm.images.concat(this.imageList,this.imagesReceive)
           let imglist = new Set(this.basicForm.images);  // arr变成了set的数据结构，并去除了其中重复的元素
            this.basicForm.images =  Array.from(imglist);
          console.log(this.basicForm.images);
          
  
          
          let dataList = {
            ...this.basicForm,
          }
          
         if(this.isEdit){ 
          
           /* if(dataList.images.length===0){
             
          delete dataList.images
           } */
                
          putProductDetail(this.$route.params.id,dataList).then((res)=>{
            console.log(res);
            if(res.code == 0){
             
              this.$emit('replaceSpecs',"second");
              this.getDetail(this.$route.params.id)
              // this.dialogVisible = false;
              this.$refs.uploadFile.clearFiles()
              this.imageList = [];
              console.log(this.dialogVisible);
              
              this.$notify({
                message: '编辑产品基础信息成功',
                type: 'success',
                duration: 2000,
              })
            }else{
             
              this.$notify({
                message: res.msg,
                type: 'error',
                duration: 2000,
              })
            }
          })
        } 
         else{
           addProduct(dataList).then(res => {
          console.log(res);
          if(res.code == 0){
              
              this.$emit('replaceSpecs',"second");
              this.$emit('backProductId',res.data.product_id)
              this.$emit('showBasicNum',false)
              this.getDetail(res.data.product_id)
              // this.dialogVisible = false;
               this.$refs.uploadFile.clearFiles()
               this.imageList = [];
              this.$notify({
                message: '添加产品基础信息成功',
                type: 'success',
                duration: 2000,
              })
            }else{
              
              
              this.$notify({
                message: res.msg,
                type: 'error',
                duration: 2000,
              })
            }
      })
        }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
     //上传图片成功后的狗子
    successHandle(res, file, fileList) {
      console.log(1, res)
      console.log(2, file)
      console.log(3, fileList)
      this.imageList.push({'name':res.data.name,'url':res.data.relative_url})
    console.log(this.imageList);
    
    },

    // 上传图片超出限制
    handleExceed() {
      console.log('上传文件超出12个')
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.imageList.forEach((value,index,array)=>{

        if(value.name == file.name){

          this.imageList.splice(index,1)


        }  })
        console.log(this.imageList);

    },
    handlePictureCardPreview(file) {
      // this.productForm.images.url = file.url
      console.log(77777);
      if(this.basicForm.images){
        this.basicForm.images.image_url = file.url
      }
      
      this.dialogVisible = true;
      console.log(file)
    },
    beforeAvatarUpload(file, fileList) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传产品图片大小不能超过 1MB!')
      }
      return isLt1M
    },
  }
}
</script>

<style lang="scss" scoped>
  .el-tabs__nav-wrap{
    background-color:#DEDEE4;
    padding-left:20px;
  }
  .price-flex{
    display:flex;
    flex-flow:row wrap

  }
  .price-flex label{
    flex: 0 1 auto;
    margin:10px
  }
  .small-input{
    width:50%;
    margin:10px;
  }
  .form-con{
    padding: 1% 10% 5% 0;
    .product-border{
    border: 1px solid #eee;
    
    margin-bottom: 20px;
    h2{
      background-color: #eee;
      margin: 0;
      padding: 10px 0 10px 20px;
    }
    .form-main{
      padding: 2% 10%;
    }
  }
  }


  .add-product{
    margin-bottom: 20px;
    background-color: #eee;
    padding: 10px 0 10px 15px;
  }
  .disc-button{
    color: #1890ff;
    border-color: #1890ff;
  }
  .form-middle{
    position: fixed;
    bottom: 10px;
    left: 40%;
    background-color: #fff;
  }
  .receive-image{
    width: 450px;
    height: 165px;
    display: inline-flex;
    overflow-x: auto;
    margin-top: 0;
    li{
    display: inline-block;
      width: 148px;
      height: 148px;
      position: relative;
      border: 1px solid #eee;
      margin: 0 5px;
      .delete-img{
        cursor: pointer;
        position:absolute;
        right: 10%;
        top: 5%;
        width: 5px;
        height: 5px;
      }
    }
  }
</style>
